package service

import (
	"context"
	"fmt"
	__ "learn-server/basic/proto"
	"learn-server/handler/models"
	"learn-server/untils"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedUserServer
}

// 登录
// SayHello implements helloworld.GreeterServer
func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	var user models.User
	user.Username = in.Username
	user.Password = in.Password
	if err := user.GetUserInfo(); err != nil {
		return nil, err
	}
	if user.Id == 0 {
		return nil, fmt.Errorf("用户不存在，禁止登录")
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("密码错误，请重新输入")
	}

	return &__.LoginResp{
		Id: int64(user.Id),
	}, nil
}

// 用户支付
func (s *Server) UserPay(_ context.Context, in *__.UserPayReq) (*__.UserPayResp, error) {
	var order models.Order
	order.Id = uint(in.OrderId)
	if err := order.GetOrderInfo(); err != nil {
		return nil, err
	}
	if order.Id == 0 {
		return nil, fmt.Errorf("该订单不存在")
	}
	aliPay := untils.Ali{}
	money := fmt.Sprintf("%.2d", order.OrderPrice)
	return &__.UserPayResp{
		PayUrl: aliPay.Alipay(order.OrderSn, money),
	}, nil
}

// 课程
func (s *Server) ClassList(_ context.Context, in *__.ClassListReq) (*__.ClassListResp, error) {
	var classLists []*__.ClassList
	var cla models.Class

	list, err := cla.GetClassList()
	if err != nil {
		return nil, fmt.Errorf("课程展示失败")
	}
	for _, class := range list {
		classLists = append(classLists, &__.ClassList{
			Id:           int64(class.Id),
			ClassName:    class.ClassName,
			ClassTeacher: class.ClassTeacher,
			Price:        int64(class.Price),
			ClassDesc:    class.ClassDesc,
			ClassStatus:  int64(class.ClassStatus),
		})
	}
	return &__.ClassListResp{
		List: classLists,
	}, nil
}

// 订单
func (s *Server) OrderDetail(_ context.Context, in *__.OrderDetailReq) (*__.OrderDetailResp, error) {
	var order models.Order
	order.Id = uint(in.Id)
	if err := order.GetOrderDetail(); err != nil {
		return nil, fmt.Errorf("订单详情展示失败")
	}
	return &__.OrderDetailResp{
		Id:          int64(order.Id),
		OrderSn:     order.OrderSn,
		UserId:      int64(order.UserId),
		ClassId:     int64(order.ClassId),
		OrderPrice:  int64(order.OrderPrice),
		OrderStatus: int64(order.OrderStatus),
	}, nil
}

// 创建订单
func (s *Server) CreateOrder(_ context.Context, in *__.CreateOrderReq) (*__.CreateOrderResp, error) {
	order := models.Order{
		OrderSn:     in.OrderSn,
		UserId:      uint(in.UserId),
		ClassId:     uint(in.ClassId),
		OrderPrice:  uint(in.OrderPrice),
		OrderStatus: uint(in.OrderStatus),
	}
	if err := order.CreateOrder(); err != nil {
		return nil, fmt.Errorf("订单创建失败")
	}
	return &__.CreateOrderResp{
		Id: int64(order.Id),
	}, nil
}
